package com.rchat.pocmini.activity.adapter;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.rchat.pocmini.R;
import com.rchat.pocmini.account.PocAccount;
import com.rchat.pocmini.activity.bean.PushMessageOffLineBean;
import com.rchat.pocmini.activity.fragment.FriendFragment;
import com.rchat.pocmini.global.HttpCodeGlobal;
import com.rchat.pocmini.global.RequestParam;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.util.HttpUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ljd on 2017/4/13.
 */

public class PushMessageOffLineAdapter extends BaseAdapter {

    private List<PushMessageOffLineBean> dataList;
    private Context context;
    private LayoutInflater inflater;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 1:
                    String backJson = (String) msg.obj;
                    if (backJson == null || backJson.equals("")) {
                        break;
                    }
                    try {
                        JSONObject obj = new JSONObject(backJson);
                        if (obj.getString("code").equals("200")) {
                            if (AirtalkeeAccount.getInstance().isAccountRunning()) {
                                FriendFragment.instance.queryFriend();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            }
        }
    };

    public PushMessageOffLineAdapter(Context context, List<PushMessageOffLineBean> dataList) {
        this.dataList = dataList;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return dataList.get(position).getType();
    }

    @Override
    public Object getItem(int position) {

        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return 5;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ApplyGroupViewHolder applyGroupViewHolder = null;
        ApplyFriendViewHolder applyFriendViewHolder = null;
        ReplyFriendViewHolder replyFriendViewHolder = null;
        ReplyGroupViewHolder replyGroupViewHolder = null;
        InviteMemberViewHolder inviteMemberViewHolder = null;

        final PushMessageOffLineBean bean = dataList.get(position);

        int temp = -1;
        if (convertView != null) {
            if (convertView.getTag() instanceof ApplyGroupViewHolder) {
                temp = PushMessageOffLineBean.APPLY_GROUP;
            } else if (convertView.getTag() instanceof ApplyFriendViewHolder) {
                temp = PushMessageOffLineBean.APPLY_FRIEND;
            } else if (convertView.getTag() instanceof ReplyFriendViewHolder) {
                temp = PushMessageOffLineBean.REPLY_FRIEND;
            } else if (convertView.getTag() instanceof ReplyGroupViewHolder) {
                temp = PushMessageOffLineBean.REPLY_GROUP;
            } else if (convertView.getTag() instanceof InviteMemberViewHolder) {
                temp = PushMessageOffLineBean.INVITE_MEMBER;
            }
        }

        if (temp != getItemViewType(position)) {
            convertView = null;
        }


        if (null == convertView) {
            switch (getItemViewType(position)) {
                case PushMessageOffLineBean.APPLY_GROUP:
                    convertView = inflater.inflate(R.layout.push_message_offline_list_view_item_apply_group, null);
                    applyGroupViewHolder = new ApplyGroupViewHolder();
                    applyGroupViewHolder.tvDisplayName = (TextView) convertView.findViewById(R.id.tv_display_name);
                    applyGroupViewHolder.tvCreateTime = (TextView) convertView.findViewById(R.id.tv_create_time);
                    applyGroupViewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message);
                    applyGroupViewHolder.btnAgree = (Button) convertView.findViewById(R.id.btn_agree);
                    convertView.setTag(applyGroupViewHolder);
                    break;
                case PushMessageOffLineBean.APPLY_FRIEND:
                    convertView = inflater.inflate(R.layout.push_message_offline_list_view_item_apply_friend, null);
                    applyFriendViewHolder = new ApplyFriendViewHolder();
                    applyFriendViewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message);
                    applyFriendViewHolder.tvDisplayName = (TextView) convertView.findViewById(R.id.tv_display_name);
                    applyFriendViewHolder.tvCreateTime = (TextView) convertView.findViewById(R.id.tv_create_time);
                    applyFriendViewHolder.btnAgree = (Button) convertView.findViewById(R.id.btn_agree);
                    convertView.setTag(applyFriendViewHolder);
                    break;
                case PushMessageOffLineBean.REPLY_FRIEND:
                    convertView = inflater.inflate(R.layout.push_message_offline_list_view_item_reply_friend, null);
                    replyFriendViewHolder = new ReplyFriendViewHolder();
                    replyFriendViewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message);
                    replyFriendViewHolder.tvCreateTime = (TextView) convertView.findViewById(R.id.tv_create_time);

                    convertView.setTag(replyFriendViewHolder);
                    break;
                case PushMessageOffLineBean.REPLY_GROUP:
                    convertView = inflater.inflate(R.layout.push_message_offline_list_view_item_reply_group, null);
                    replyGroupViewHolder = new ReplyGroupViewHolder();
                    replyGroupViewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message);
                    replyGroupViewHolder.tvCreateTime = (TextView) convertView.findViewById(R.id.tv_create_time);
                    convertView.setTag(replyGroupViewHolder);
                    break;
                case PushMessageOffLineBean.INVITE_MEMBER:
                    convertView = inflater.inflate(R.layout.push_message_offline_list_view_item_invite_member, null);
                    inviteMemberViewHolder = new InviteMemberViewHolder();
                    inviteMemberViewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message);
                    inviteMemberViewHolder.tvCreateTime = (TextView) convertView.findViewById(R.id.tv_create_time);
                    convertView.setTag(inviteMemberViewHolder);
                    break;
            }
        } else {
            switch (getItemViewType(position)) {
                case PushMessageOffLineBean.APPLY_GROUP:
                    applyGroupViewHolder = (ApplyGroupViewHolder) convertView.getTag();
                    break;
                case PushMessageOffLineBean.APPLY_FRIEND:
                    applyFriendViewHolder = (ApplyFriendViewHolder) convertView.getTag();
                    break;
                case PushMessageOffLineBean.REPLY_FRIEND:
                    replyFriendViewHolder = (ReplyFriendViewHolder) convertView.getTag();
                    break;
                case PushMessageOffLineBean.REPLY_GROUP:
                    replyGroupViewHolder = (ReplyGroupViewHolder) convertView.getTag();
                    break;
                case PushMessageOffLineBean.INVITE_MEMBER:
                    inviteMemberViewHolder = (InviteMemberViewHolder) convertView.getTag();
                    break;

            }
        }

        switch (getItemViewType(position)) {
            case PushMessageOffLineBean.APPLY_GROUP:
                if (applyGroupViewHolder == null) {
                    break;
                }
                applyGroupViewHolder.tvDisplayName.setText(bean.getDisplayName());
                applyGroupViewHolder.tvCreateTime.setText(bean.getCreateTime());
                applyGroupViewHolder.tvMessage.setText(bean.getDisplayName() + "请求加入您的群组\"" + bean.getGroupName() + "\"");
                final ApplyGroupViewHolder finalApplyGroupViewHolder = applyGroupViewHolder;
                applyGroupViewHolder.btnAgree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //同意加群组
                        String requestJson = createAgreeJoinGroupJson(bean.getGroupId(), bean.getUserName(), 0);
                        startAgreeThread(requestJson, UrlsGlobal.getUrl(UrlsGlobal.AGREE_JOIN_GROUP));
                        finalApplyGroupViewHolder.btnAgree.setBackgroundColor(Color.parseColor("#dadbdd"));
                        finalApplyGroupViewHolder.btnAgree.setText("已同意");
                    }
                });
                break;
            case PushMessageOffLineBean.APPLY_FRIEND:
                if (applyFriendViewHolder == null) {
                    break;
                }
                applyFriendViewHolder.tvCreateTime.setText(bean.getCreateTime());
                applyFriendViewHolder.tvDisplayName.setText(bean.getDisplayName());
                applyFriendViewHolder.tvMessage.setText(bean.getDisplayName() + "请求加您为好友");
                final ApplyFriendViewHolder finalApplyFriendViewHolder = applyFriendViewHolder;
                applyFriendViewHolder.btnAgree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //同意添加好友
                        String requestJson = createAgreeAddFriendJson(PocAccount.getUserId(), bean.getUserName(), 0);
                        startAgreeThread(requestJson, UrlsGlobal.getUrl(UrlsGlobal.AGREE_ADD_FRIEND));
                        finalApplyFriendViewHolder.btnAgree.setBackgroundColor(Color.parseColor("#dadbdd"));
                        finalApplyFriendViewHolder.btnAgree.setText("已同意");
                    }
                });
                break;
            case PushMessageOffLineBean.REPLY_FRIEND:
                if (replyFriendViewHolder == null) {
                    break;
                }
                replyFriendViewHolder.tvMessage.setText(bean.getMessage());
                replyFriendViewHolder.tvCreateTime.setText(bean.getCreateTime());
                break;
            case PushMessageOffLineBean.REPLY_GROUP:
                if (replyGroupViewHolder == null) {
                    break;
                }
                replyGroupViewHolder.tvMessage.setText(bean.getMessage());
                replyGroupViewHolder.tvCreateTime.setText(bean.getCreateTime());
                break;
            case PushMessageOffLineBean.INVITE_MEMBER:
                if (inviteMemberViewHolder == null) {
                    break;
                }
                inviteMemberViewHolder.tvMessage.setText(bean.getMessage());
                inviteMemberViewHolder.tvCreateTime.setText(bean.getCreateTime());
                break;

        }
        return convertView;
    }


    /**
     * 生成同意加好友请求json
     *
     * @return 请求json
     */
    private String createAgreeAddFriendJson(String userName, String otherName, int isAgree) {
        Map<String, String> param = new HashMap<>();
        param.put("userName", userName);
        param.put("otherName", otherName);
        param.put("isagree", isAgree + "");
        //body = {"code":1033,"data":{"platform":1,"version":"1.0","enterprise":1,"otherName":"111110000088","isagree":"0","userName":"111110000118"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1033, param);
        return body;
    }

    /**
     * 生成同意加入群组请求json
     *
     * @return 请求json
     */
    private String createAgreeJoinGroupJson(String groupId, String userName, int isAgree) {
        Map<String, String> param = new HashMap<>();
        param.put("groupId", groupId);
        param.put("userName", userName);
        param.put("isagree", isAgree + "");

        //body = {"code":1026,"data":{"platform":1,"version":"1.0","enterprise":1,"groupId":"C20793","isagree":"0","userName":"111110000111"}}
        String body = RequestParam.requestRootParam(HttpCodeGlobal.REQ_CODE_1026, param);
        return body;
    }

    private void startAgreeThread(final String requestJson, final String url) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                String backJson = HttpUtil.httpConnect(url, requestJson, HttpUtil.HTTP_POST);
                Message m = new Message();
                if (url.equals(UrlsGlobal.getUrl(UrlsGlobal.AGREE_ADD_FRIEND))) {
                    m.what = 1;
                    m.obj = backJson;
                    handler.sendMessage(m);
                }
            }
        };
        thread.start();
    }

    private static class ApplyGroupViewHolder {
        private TextView tvDisplayName;
        private TextView tvUserName;
        private TextView tvCreateTime;
        private TextView tvGroupName;
        private TextView tvGroupId;
        private TextView tvMessage;
        private Button btnAgree;

    }

    private static class ApplyFriendViewHolder {
        private TextView tvDisplayName;
        private TextView tvUserName;
        private TextView tvCreateTime;
        private TextView tvMessage;
        private Button btnAgree;

    }

    private static class ReplyFriendViewHolder {
        private TextView tvMessage;
        private TextView tvCreateTime;

    }

    private static class ReplyGroupViewHolder {
        private TextView tvMessage;
        private TextView tvCreateTime;
    }

    private static class InviteMemberViewHolder {
        private TextView tvMessage;
        private TextView tvCreateTime;
    }

}
